<template>
  <div class="voice-chat-container">
    <h2>语音聊天室</h2>

    <div class="controls">
      <button @click="startRecording" :disabled="isRecording">开始录音</button>
      <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
      <button @click="playRecording" :disabled="!audioBlob">播放录音</button>
      <button @click="sendRecording" :disabled="!audioBlob">发送录音</button>
      <button @click="saveRecording" :disabled="!audioBlob">保存录音</button>

      <input
          type="file"
          id="audioFileInput"
          accept=".wav,audio/*"
          @change="loadRecording"
          style="display: none"
      >
      <button @click="triggerFileInput">加载录音</button>
    </div>

    <div ref="waveform" class="waveform"></div>

    <div class="received-audios">
      <h3>收到的语音消息</h3>
      <div v-for="(audio, index) in receivedAudios" :key="index" class="audio-message">
        <p>消息 {{ index + 1 }} - {{ audio.name || '未命名' }}</p>
        <audio controls :src="audio.url"></audio>
        <button @click="deleteAudio(index)">删除</button>
        <button @click="saveReceivedAudio(index)">保存</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import RecordRTC from 'recordrtc';
import WaveSurfer from 'wavesurfer.js';
import io from 'socket.io-client';

// 状态管理
const isRecording = ref(false);
const audioBlob = ref(null);
const receivedAudios = ref([]);
const waveform = ref(null);
const wavesurfer = ref(null);
const recorder = ref(null);
const socket = ref(null);

// 初始化 Wavesurfer
onMounted(() => {
  wavesurfer.value = WaveSurfer.create({
    container: waveform.value,
    waveColor: '#4a4a88',
    progressColor: '#2c3e50',
    cursorColor: '#2c3e50',
    barWidth: 2,
    barRadius: 3,
    cursorWidth: 1,
    height: 100,
    barGap: 2,
    responsive: true
  });

  // 初始化 Socket.IO 连接
  socket.value = io('http://localhost:3000');

  socket.value.on('audio-message', (audioData) => {
    const audioBlob = new Blob([new Uint8Array(audioData.data)], { type: 'audio/wav' });
    const audioUrl = URL.createObjectURL(audioBlob);
    receivedAudios.value.push({
      url: audioUrl,
      blob: audioBlob,
      name: audioData.name || `语音消息_${new Date().toLocaleString()}`
    });
  });

  // 尝试加载本地存储的录音
  loadFromLocalStorage();
});

// 清理资源
onBeforeUnmount(() => {
  if (wavesurfer.value) {
    wavesurfer.value.destroy();
  }
  if (socket.value) {
    socket.value.disconnect();
  }
});

// 开始录音
const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    recorder.value = new RecordRTC(stream, {
      type: 'audio',
      mimeType: 'audio/wav',
      recorderType: RecordRTC.StereoAudioRecorder,
      desiredSampRate: 16000,
      numberOfAudioChannels: 1,
      timeSlice: 1000,
      ondataavailable: (blob) => {
        // 实时传输时可以在这里发送数据块
      }
    });

    recorder.value.startRecording();
    isRecording.value = true;
  } catch (error) {
    console.error('无法访问麦克风:', error);
    alert('无法访问麦克风，请检查权限设置');
  }
};

// 停止录音
const stopRecording = () => {
  if (recorder.value) {
    recorder.value.stopRecording(() => {
      audioBlob.value = recorder.value.getBlob();
      wavesurfer.value.load(URL.createObjectURL(audioBlob.value));
      isRecording.value = false;
    });
  }
};

// 播放录音
const playRecording = () => {
  if (audioBlob.value) {
    wavesurfer.value.play();
  }
};

// 发送录音
const sendRecording = () => {
  if (!audioBlob.value || !socket.value) return;

  const reader = new FileReader();
  reader.onload = () => {
    const arrayBuffer = reader.result;
    const name = prompt('请输入语音消息名称', `语音消息_${new Date().toLocaleString()}`);
    socket.value.emit('audio-message', {
      data: Array.from(new Uint8Array(arrayBuffer)),
      name: name || undefined
    });
  };
  reader.readAsArrayBuffer(audioBlob.value);
};

// 删除收到的音频
const deleteAudio = (index) => {
  URL.revokeObjectURL(receivedAudios.value[index].url);
  receivedAudios.value.splice(index, 1);
  saveToLocalStorage();
};

// 保存当前录音到本地文件
const saveRecording = () => {
  if (!audioBlob.value) return;

  const name = prompt('请输入保存的文件名', `录音_${new Date().toLocaleString()}.wav`);
  if (!name) return;

  const url = URL.createObjectURL(audioBlob.value);
  const a = document.createElement('a');
  a.href = url;
  a.download = name.endsWith('.wav') ? name : `${name}.wav`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

// 触发文件选择对话框
const triggerFileInput = () => {
  const fileInput = document.getElementById('audioFileInput');
  fileInput.value = ''; // 清除之前的选择
  fileInput.click();
};

// 从文件加载录音
const loadRecording = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  if (!file.type.startsWith('audio/') && !file.name.endsWith('.wav')) {
    alert('请选择有效的音频文件');
    return;
  }

  const reader = new FileReader();
  reader.onload = (e) => {
    const arrayBuffer = e.target.result;
    const blob = new Blob([arrayBuffer], { type: file.type || 'audio/wav' });
    audioBlob.value = blob;
    wavesurfer.value.load(URL.createObjectURL(blob));
  };
  reader.readAsArrayBuffer(file);
};

// 保存收到的音频到本地文件
const saveReceivedAudio = (index) => {
  const audio = receivedAudios.value[index];
  const name = prompt('请输入保存的文件名', `${audio.name || '语音消息'}.wav`);
  if (!name) return;

  const a = document.createElement('a');
  a.href = audio.url;
  a.download = name.endsWith('.wav') ? name : `${name}.wav`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// 保存收到的音频到本地存储
const saveToLocalStorage = () => {
  const audiosToSave = receivedAudios.value.map(audio => ({
    name: audio.name,
    data: Array.from(new Uint8Array(audio.blob))
  }));
  localStorage.setItem('savedAudios', JSON.stringify(audiosToSave));
};

// 从本地存储加载音频
const loadFromLocalStorage = () => {
  const savedAudios = localStorage.getItem('savedAudios');
  if (savedAudios) {
    try {
      const parsedAudios = JSON.parse(savedAudios);
      parsedAudios.forEach(audio => {
        const audioBlob = new Blob([new Uint8Array(audio.data)], { type: 'audio/wav' });
        const audioUrl = URL.createObjectURL(audioBlob);
        receivedAudios.value.push({
          url: audioUrl,
          blob: audioBlob,
          name: audio.name
        });
      });
    } catch (e) {
      console.error('加载本地存储的音频失败:', e);
      localStorage.removeItem('savedAudios');
    }
  }
};
</script>

<style scoped>
/* 之前的样式保持不变，可以添加以下样式 */
input[type="file"] {
  display: none;
}

.audio-message button {
  margin-left: 5px;
  padding: 4px 8px;
  font-size: 0.8em;
}
</style>